<?php
class JBShopRoles {
	public static function checkFunction($user, $function) {
		$db = & JFactory :: getDBO();
		$query = "SELECT " .
				"	f.name AS function_name, " .
				"	u.system_user_id AS user_id, " .
				"	su.username AS username " .
				"FROM " .
				"	#__jbshop_functions f " .
				"	Inner Join #__jbshop_roles_functions rf ON f.id = rf.function_id " .
				"	Inner Join #__jbshop_users u ON u.tsb_role_id = rf.role_id " .
				"	Inner Join #__users su ON u.system_user_id = su.id " .
				"WHERE " .
				"	u.system_user_id = '". $user->id ."' AND f.name = '".$function."'";

		$db->setQuery($query);
		$result = $db->loadResult();
		return $result != null;
	}

	/*
	 * Check access permission to a function of current login user
	 *
	 * */
	public static function checkPermission($controller, $function, $redirectUrl, $message = null, $redirect = true){
		//Super Administrator always have full access
		if (JBShopRoles::isSuperAdmin()){
			return true;
		}

		//If no permission
		if (!TSBRoles::checkFunction(JFactory :: getUser(), $function)) {
			if($message == null)
				$msg = JText :: _('_CAL_LANG_NOPERMISSION');
			else
				$msg = JText :: _($message);

			//Redirect the page
			if($redirect){
				$redirectURL = empty($redirectURL) ? 'index.php?option=com_jbshop' : $redirectURL;
				$controller->setRedirect($redirectURL, $msg);
			}

			return false;
		}
		return true;
	}

	/*
	 * Check if loged in user is Super Administrtor or not
	 * */

	 public static function isSuperAdmin(){
		$user = & JFactory::getUser();
		return ($user->get('usertype') == 'Super Administrator');
	 }
}
?>